package com.accum.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.accum.client.GreetingService;
import com.accum.shared.FieldVerifier;
import com.accum.shared.pojo.WordEntry;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.dev.shell.WorkDirs;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	private static final Logger log = Logger.getLogger(GreetingServiceImpl.class.getName());
	
	private List<String> entries = new ArrayList<String>();
	private List<WordEntry> wordEntries = new ArrayList<WordEntry>();
	
	
	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}

	@Override
	public Boolean addEntry(String entryName) {
		this.entries.add(entryName);
		return true;
	}

	@Override
	public List<String> getEntries() {
		
		if(entries.size() < 1){
			entries.add("testing1");
		}
		return this.entries;
	}

	@Override
	public WordEntry addWordEntry(WordEntry entry) {
		
		User user = null; //= authenticate();
		
		entry.setCreateDate(new Date());
		if(user != null){
			entry.setUserEmail(user.getEmail());
		}else{
			entry.setUserEmail("lovelywib@gmail.com");
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.makePersistent(entry);
		}catch(Exception ex){
			log.log(Level.WARNING, "fail to persist WordEntry", ex);
		}finally{
			pm.close();
		}
		
		return entry;
	}

	@Override
	public List<WordEntry> searchEntries(Map<String, Object> params) {

		List<WordEntry> retList = new LinkedList<WordEntry>();
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		String query = "select from " + WordEntry.class.getName() + " order by createDate desc";
		List<WordEntry> results =  (List<WordEntry>) pm.newQuery(query).execute();
		
		for(WordEntry obj : results){
			retList.add(obj);
		}
		
		return retList;
	}
	
	
	public User authenticate(){
		
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if(user == null){
	        try {
				perThreadResponse.get().sendRedirect(userService.createLoginURL(perThreadRequest.get().getRequestURI()));
			} catch (IOException e) {
				log.log(Level.WARNING, e.getMessage(), e);
			}
        }	
        
        return user;        
	}	

}